package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.mapper.CategoryMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    HttpServletRequest request;

    @Autowired
    JwtProperties jwtProperties;

    @Override
    public List<Category> selectByType(Integer type) {
        List<Category> categories = categoryMapper.selectByType(type);
        List<Category> categoryList = new ArrayList<>();
        categories.forEach((item)->{
            if (item.getStatus()==1){
                categoryList.add(item);
            }
        });
        return categoryList;
    }

    @Override
    public PageResult selectByPage(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(), categoryPageQueryDTO.getPageSize());
        List<Category> categories = categoryMapper.selectByPage(categoryPageQueryDTO);
        Page<Category> categoryPage = (Page<Category>) categories;
        PageResult pageResult = new PageResult(categoryPage.getTotal(), categoryPage.getResult());
        return pageResult;
    }

    @Override
    public void updateById(CategoryDTO categoryDTO) {

        Long userId = BaseContext.getCurrentId();

        Category category = new Category();

        BeanUtils.copyProperties(categoryDTO,category);

        categoryMapper.updateById(category);
    }

    @Override
    public void setStatusById(Integer status, Long id) {
        Category category = Category.builder()
                .status(status)
                .id(id)
                .build();
       categoryMapper.updateById(category);
    }

    @Override
    public void insert(CategoryDTO categoryDTO) {

        Long userId = BaseContext.getCurrentId();
        //实体类使用了@Builder注解，所以可以这样创建对象并初始化
        Category category = Category.builder()
                .status(0)
                .build();

        BeanUtils.copyProperties(categoryDTO, category);


        categoryMapper.insert(category);
    }

    @Override
    public void deleteById(Integer id) {
        categoryMapper.deleteById(id);
    }

    @Override
    public List<Category> selectAll() {

        List<Category> list= categoryMapper.selectAll();
        return list;
    }
}
